#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
魔兽争霸3自动对战AI系统 - GUI启动脚本

此脚本用于启动系统的图形用户界面，提供可视化操作界面。
"""

import os
import sys
import subprocess
import time
import logging

# 确保必要的目录存在
def ensure_directories():
    """确保必要的目录结构存在"""
    directories = [
        "data/logs",
        "data/models",
        "data/templates",
        "data/screenshots"
    ]
    
    for directory in directories:
        os.makedirs(directory, exist_ok=True)
        print(f"确保目录存在: {directory}")

# 首先确保必要的目录存在
ensure_directories()

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("data/logs/start_gui.log", encoding='utf-8'),
        logging.StreamHandler()
    ]
)

# 检查Python环境
def check_python_environment():
    """检查Python环境和必要的依赖"""
    logging.info(f"Python版本: {sys.version}")
    
    # 检查必要的包
    required_packages = [
        {"name": "PyQt5", "import": "PyQt5"},
        {"name": "numpy", "import": "numpy"},
        {"name": "opencv-python", "import": "cv2"},
        {"name": "pyautogui", "import": "pyautogui"},
        {"name": "pydirectinput", "import": "pydirectinput"},
        {"name": "tensorflow", "import": "tensorflow"},
        {"name": "matplotlib", "import": "matplotlib"}
    ]
    
    missing_packages = []
    for package in required_packages:
        try:
            __import__(package["import"])
            logging.info(f"✅ 已安装: {package['name']}")
        except ImportError:
            logging.warning(f"❌ 未安装: {package['name']}")
            missing_packages.append(package['name'])
    
    if missing_packages:
        logging.warning(f"发现未安装的依赖包: {missing_packages}")
        logging.warning("请确保已激活正确的conda环境并安装了所有依赖")
    
    return len(missing_packages) == 0

# 启动GUI应用
def start_gui_application():
    """启动GUI应用程序"""
    try:
        logging.info("正在启动魔兽争霸3自动对战AI系统...")
        
        # 检查gui_app.py是否存在
        gui_script = "gui_app.py"
        if not os.path.isfile(gui_script):
            raise FileNotFoundError(f"找不到GUI应用脚本: {gui_script}")
        
        logging.info(f"执行脚本: {gui_script}")
        
        # 使用subprocess启动应用
        process = subprocess.Popen(
            [sys.executable, gui_script],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        # 打印输出
        def print_output(pipe, prefix):
            for line in iter(pipe.readline, ''):
                print(f"[{prefix}] {line.strip()}")
        
        # 启动线程读取标准输出和错误
        import threading
        stdout_thread = threading.Thread(
            target=print_output, 
            args=(process.stdout, "GUI"),
            daemon=True
        )
        stderr_thread = threading.Thread(
            target=print_output, 
            args=(process.stderr, "GUI-ERROR"),
            daemon=True
        )
        
        stdout_thread.start()
        stderr_thread.start()
        
        # 等待进程完成
        process.wait()
        
        # 等待输出线程完成
        stdout_thread.join(timeout=1.0)
        stderr_thread.join(timeout=1.0)
        
        logging.info(f"GUI应用已退出，返回代码: {process.returncode}")
        return process.returncode
        
    except Exception as e:
        logging.error(f"启动GUI应用失败: {e}")
        print(f"错误: 启动应用失败 - {str(e)}")
        return 1

# 主函数
def main():
    """主函数"""
    print("\n=== 魔兽争霸3自动对战AI系统启动器 ===\n")
    
    # 确保必要的目录存在
    ensure_directories()
    
    # 检查Python环境
    print("检查Python环境...")
    environment_ok = check_python_environment()
    
    if not environment_ok:
        input("\n按Enter键继续启动...")
    
    # 启动GUI应用
    print("\n启动图形用户界面...")
    return start_gui_application()


if __name__ == "__main__":
    sys.exit(main())